package com.micro.school.order.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.core.utils.SecurityContextHolderUtils;
import com.micro.school.common.core.utils.poi.ExcelUtil;
import com.micro.school.common.core.web.controller.BaseController;
import com.micro.school.common.core.web.domain.AjaxResult;
import com.micro.school.common.core.web.page.TableDataInfo;
import com.micro.school.common.log.annotation.Log;
import com.micro.school.common.log.enums.BusinessType;
import com.micro.school.common.security.utils.SecurityUtils;
import com.micro.school.order.domain.PayStudentFeePaymentDetail;
import com.micro.school.order.entity.*;
import com.micro.school.order.service.IPayFeeItemConfigService;
import com.micro.school.order.service.IPayStudentFeePaymentDetailService;
import com.micro.school.order.service.IStudentService;
import com.micro.school.order.vo.PayStudentFeePaymentDetailExcelVo;
import com.micro.school.order.vo.PayStudentFeePaymentExcelVo;
import com.micro.school.order.vo.PayStudentFeePaymentPreVo;
import com.micro.school.system.api.domain.StudentInfos;
import com.micro.school.system.api.domain.vo.PayStudentFeePaymentVos;
import com.micro.school.system.api.domain.vo.PayStudentPrepaymentVos;
import com.micro.school.system.api.model.LoginUser;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.micro.school.order.domain.PayStudentFeePayment;
import com.micro.school.order.service.IPayStudentFeePaymentService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 支付单Controller
 * 
 * @author lyb
 * @date 2025-08-19
 */
@RestController
@RequestMapping("/pay/payStudentFeePayment")
public class PayStudentFeePaymentController extends BaseController
{
    @Autowired
    private IPayStudentFeePaymentService payStudentFeePaymentService;

    @Autowired
    private IPayStudentFeePaymentDetailService detailService;

    @Autowired
    private IPayFeeItemConfigService feeItemConfigService;

    @Autowired
    private IStudentService studentService;


    /**
     * 查询支付单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PayStudentFeePayment payStudentFeePayment)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payStudentFeePayment.setTenantId(loginUser.getSysUser().getTenantId());
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            payStudentFeePayment.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            payStudentFeePayment.setCollegeIds(SecurityContextHolderUtils.getCollegeId() != null && SecurityContextHolderUtils.getCollegeId().length > 0 ? SecurityContextHolderUtils.getCollegeId(): null);
        }
        startPage();
        List<PayStudentFeePayment> list = payStudentFeePaymentService.selectPayStudentFeePaymentList(payStudentFeePayment);
        fillStatus(list);
        return getDataTable(list);
    }
    private void fillStatus(List<PayStudentFeePayment> list){
        if(null==list || list.isEmpty()){
            return;
        }
        List<Long> studentIds = list.stream()
                .map(PayStudentFeePayment::getStudentId)        // 提取 studentId
                .filter(studentId -> studentId != null)         // 过滤掉 null 值
                .collect(Collectors.toList());
        Map<Long, StudentInfos> studentInfosMap = studentService.queryStudentByIds(studentIds);
        StudentEntity.setStudentStatus(list,studentInfosMap);
        for(PayStudentFeePayment detail:list){
            detail.setPayMethodName(PayMethodStaticEntity.getPayMethodName(detail));
        }
    }

    /**
     * 预缴费明细
     */
    @GetMapping("/prePayment/list")
    public TableDataInfo prePaymentList(PayStudentFeePayment payStudentFeePayment)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payStudentFeePayment.setTenantId(loginUser.getSysUser().getTenantId());
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            payStudentFeePayment.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            payStudentFeePayment.setCollegeIds(SecurityContextHolderUtils.getCollegeId() != null && SecurityContextHolderUtils.getCollegeId().length > 0 ? SecurityContextHolderUtils.getCollegeId(): null);
        }
        startPage();
        List<PayStudentFeePaymentPreVo> list = payStudentFeePaymentService.selectPrepaymenttList(payStudentFeePayment);
        if(null!=list){
            for(PayStudentFeePaymentPreVo preVo:list){
                GraduateStatusEntity.setGraduate(preVo);
            }
        }
        return getDataTable(list);
    }
    /**
     * 预缴费明细
     */
    @GetMapping("/sumTotalAmount")
    public AjaxResult sumTotalAmount(PayStudentFeePayment payStudentFeePayment)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payStudentFeePayment.setTenantId(loginUser.getSysUser().getTenantId());
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            payStudentFeePayment.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            payStudentFeePayment.setCollegeIds(SecurityContextHolderUtils.getCollegeId() != null && SecurityContextHolderUtils.getCollegeId().length > 0 ? SecurityContextHolderUtils.getCollegeId(): null);
        }
        BigDecimal totalAmount = payStudentFeePaymentService.selectTotalAmount(payStudentFeePayment);
        Map<String,Object> result = new HashMap<>();
        result.put("totalAmount",totalAmount);
        return AjaxResult.success(result);
    }
    /**
     * 预缴费明细
     */
    @GetMapping("/preSumTotalAmount")
    public AjaxResult preSumTotalAmount(PayStudentFeePayment payStudentFeePayment)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payStudentFeePayment.setTenantId(loginUser.getSysUser().getTenantId());
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            payStudentFeePayment.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            payStudentFeePayment.setCollegeIds(SecurityContextHolderUtils.getCollegeId() != null && SecurityContextHolderUtils.getCollegeId().length > 0 ? SecurityContextHolderUtils.getCollegeId(): null);
        }
        BigDecimal totalAmount = payStudentFeePaymentService.selectPreSumTotalAmount(payStudentFeePayment);
        Map<String,Object> result = new HashMap<>();
        result.put("totalAmount",totalAmount);
        return AjaxResult.success(result);
    }
    /**
     * 导出支付单列表
     */
    @Log(title = "支付单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PayStudentFeePayment payStudentFeePayment) throws JsonProcessingException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payStudentFeePayment.setTenantId(loginUser.getSysUser().getTenantId());
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            payStudentFeePayment.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            payStudentFeePayment.setCollegeIds(SecurityContextHolderUtils.getCollegeId() != null && SecurityContextHolderUtils.getCollegeId().length > 0 ? SecurityContextHolderUtils.getCollegeId(): null);
        }
        List<PayStudentFeePayment> list = payStudentFeePaymentService.selectPayStudentFeePaymentList(payStudentFeePayment);
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(list);
        List<PayStudentFeePaymentExcelVo> voList = om.readValue(json, new TypeReference<>() {});
        if(null!=voList){
            for(PayStudentFeePaymentExcelVo excelVo:voList){
                excelVo.setDicRefundedStatusName();
                excelVo.setPayMethodName(PayMethodStaticEntity.getPayMethodName(excelVo));
                GraduateStatusEntity.setGraduate(excelVo);

            }
        }
        ExcelUtil<PayStudentFeePaymentExcelVo> util = new ExcelUtil<PayStudentFeePaymentExcelVo>(PayStudentFeePaymentExcelVo.class);
        util.exportExcel(response, voList, "收费支付");
    }
    /**
     * 导出支付单列表
     */
    @Log(title = "支付单", businessType = BusinessType.EXPORT)
    @PostMapping("/export/detail")
    public void exportDetail(HttpServletResponse response, PayStudentFeePayment payStudentFeePayment)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payStudentFeePayment.setTenantId(loginUser.getSysUser().getTenantId());
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            payStudentFeePayment.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            payStudentFeePayment.setCollegeIds(SecurityContextHolderUtils.getCollegeId() != null && SecurityContextHolderUtils.getCollegeId().length > 0 ? SecurityContextHolderUtils.getCollegeId(): null);
        }
        List<PayStudentFeePaymentDetailExcelVo> list = payStudentFeePaymentService.selectPaymentList(payStudentFeePayment);
        //list 学生状态
        for(PayStudentFeePaymentDetailExcelVo excelVo:list){
            GraduateStatusEntity.setGraduate(excelVo);
            PayMethodStaticEntity.setPayMethodName(excelVo);
        }
        ExcelUtil<PayStudentFeePaymentDetailExcelVo> util = new ExcelUtil<PayStudentFeePaymentDetailExcelVo>(PayStudentFeePaymentDetailExcelVo.class);
        util.exportExcel(response, list, "收费支付明细");
    }
    /**
     * 预缴费明细
     */
    @Log(title = "预缴费明细", businessType = BusinessType.EXPORT)
    @PostMapping("/pre/export")
    public void preExport(HttpServletResponse response, PayStudentFeePayment payStudentFeePayment)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payStudentFeePayment.setTenantId(loginUser.getSysUser().getTenantId());
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            payStudentFeePayment.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            payStudentFeePayment.setCollegeIds(SecurityContextHolderUtils.getCollegeId() != null && SecurityContextHolderUtils.getCollegeId().length > 0 ? SecurityContextHolderUtils.getCollegeId(): null);
        }
        List<PayStudentFeePaymentPreVo> list = payStudentFeePaymentService.selectPrepaymenttList(payStudentFeePayment);
        if(null!=list){
            for(PayStudentFeePaymentPreVo preVo: list){
                GraduateStatusEntity.setGraduate(preVo);
            }
        }
        ExcelUtil<PayStudentFeePaymentPreVo> util = new ExcelUtil<PayStudentFeePaymentPreVo>(PayStudentFeePaymentPreVo.class);
        util.exportExcel(response, list, "预缴费明细");
    }

    /**
     * 获取支付单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        PayStudentFeePayment feePayment = payStudentFeePaymentService.selectPayStudentFeePaymentById(id);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(null!=feePayment && feePayment.getTenantId().intValue()!=loginUser.getSysUser().getTenantId().intValue()){
            return AjaxResult.error();
        }
        Map<Long, PayFeeItemConfig> configMap =  feeItemConfigService.queryToMap(SecurityUtils.getIntTenantId());
        List<PayStudentFeePaymentDetail> details = detailService.selectPayStudentFeePaymentDetailByPaymentId(feePayment.getId());
        if(null!=details){
            for(PayStudentFeePaymentDetail detail:details){
                PayFeeItemConfig config = configMap.get(detail.getFeeItemConfigId());
                if(null!=config){
                    detail.setSubjectType(config.getSubjectType());
                }
                detail.setPayMethodName(PayMethodStaticEntity.getPayMethodName(detail));
                detail.setPayStatusName(PayStatusEntity.getPayMethodName(detail));
            }
        }
        feePayment.setDetails(details);
        return success(feePayment);
    }

    /**
     * 新增支付单
     */
    @Log(title = "支付单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PayStudentFeePayment payStudentFeePayment)
    {
        return toAjax(payStudentFeePaymentService.insertPayStudentFeePayment(payStudentFeePayment));
    }

    /**
     * 修改支付单
     */
    @Log(title = "支付单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PayStudentFeePayment payStudentFeePayment)
    {
        return toAjax(payStudentFeePaymentService.updatePayStudentFeePayment(payStudentFeePayment));
    }


    @PostMapping("/insertPayStudentFeePayment")
    public void insertPayStudentFeePayment(@RequestBody PayStudentFeePaymentVos payStudentFeePaymentVos){
        payStudentFeePaymentService.insertOneVos(payStudentFeePaymentVos);
    }

    /**
     * 删除支付单
     */
    @Log(title = "支付单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(payStudentFeePaymentService.deletePayStudentFeePaymentByIds(ids));
    }



    /**
     * 获取学生收费管理详细信息
     */
    @GetMapping(value = "/selectStudentFeeByStudentId")
    public AjaxResult selectStudentFeeByStudentId(@RequestParam("studentId") Long studentId,@RequestParam("feeYearId") Long feeYearId)
    {
        return success(payStudentFeePaymentService.selectStudentFeeByStudentId(studentId,feeYearId));
    }





    /**
     * 获取学生收费管理详细信息
     */
    @GetMapping(value = "/updateAllPayStudentFeePayment")
    public Map<String,Object> updateAllPayStudentFeePayment(@RequestParam("payNumber") String payNumber,@RequestParam("status") Long status)
    {
        Map<String,Object> map = payStudentFeePaymentService.updateAllPayStudentFeePayment(payNumber,status);

        return map;
    }


    /**
     * 获取学生收费管理详细信息
     */
    @GetMapping(value = "/updateStudentFeePayment")
    public AjaxResult updateStudentFeePayment(@RequestBody PayStudentFeePaymentVos payStudentFeePaymentVos)
    {
        return AjaxResult.success(payStudentFeePaymentService.updateStudentFeePayment(payStudentFeePaymentVos));
    }
}
